/*
 * Recorder.java
 *
 * Created on Dec 19, 2011, 9:36:18 PM
 */
package kinect.recorder;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import kinect.storage.KinectStorageProtos.Sequence;
//import kinect.storage.KinectStorageProtos.Frame;


/**
 *
 * @author samo
 */
public class RecorderUI extends javax.swing.JFrame {
    UserTracker userTracker;
    boolean recording;
    boolean delayTimeSet;
    boolean recordTimeSet;
    Timer delayTimer;
    Timer recordTimer;
    FileOutputStream output;
    String path = "/home/samo/recordings/";
    String fileName;
    File dir;
    boolean fileSelected;
    
    /** Creates new form Recorder */
    public RecorderUI() {
        initComponents();
    }

    public RecorderUI(UserTracker ut) {
        initComponents();
        
        // Custom
        userTracker = ut;
        userTracker.recorderUI = this;
        recording = false;
        
        jButtonStop.setEnabled(false);

        if(((Integer)jSpinnerDelay.getValue()) == 0) {
            delayTimeSet = false;
            delayTimer = new Timer(0, taskPerformerDelay);
        } else {
            delayTimeSet = true; 
            delayTimer = new Timer(1000*(Integer)jSpinnerDelay.getValue(), taskPerformerDelay);
        }
        delayTimer.setRepeats(false);
        
        if(((Integer)jSpinnerTime.getValue()) == 0) {
            recordTimeSet = false;
            recordTimer = new Timer(0, taskPerformerTimer);
        } else {
            recordTimeSet = true; 
            recordTimer = new Timer(1000*(Integer)jSpinnerTime.getValue(), taskPerformerTimer);
        }
        recordTimer.setRepeats(false);
     
        jTextFieldPath.setText(path);
        createFileName();
        jLabelFileName.setText(fileName);
        
        createFileList();
        fileSelected = false;
    }
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanelDepthPref = new javax.swing.JPanel();
        jCheckBoxDepth = new javax.swing.JCheckBox();
        jCheckBoxDepthSkeleton = new javax.swing.JCheckBox();
        jPanelRecording = new javax.swing.JPanel();
        jLabelUser = new javax.swing.JLabel();
        jTextFieldUser = new javax.swing.JTextField();
        jLabelGesture = new javax.swing.JLabel();
        jLabelSequence = new javax.swing.JLabel();
        jTextFieldGesture = new javax.swing.JTextField();
        jSpinnerSequence = new javax.swing.JSpinner();
        jSeparator1 = new javax.swing.JSeparator();
        jLabelDelay = new javax.swing.JLabel();
        jSpinnerDelay = new javax.swing.JSpinner();
        jLabelTime = new javax.swing.JLabel();
        jSpinnerTime = new javax.swing.JSpinner();
        jPanelRecButtons = new javax.swing.JPanel();
        jButtonSave = new javax.swing.JButton();
        jButtonStop = new javax.swing.JButton();
        jButtonStart = new javax.swing.JButton();
        jButtonNewSequence = new javax.swing.JButton();
        jButtonReset = new javax.swing.JButton();
        jPanelData = new javax.swing.JPanel();
        jLabelPath = new javax.swing.JLabel();
        jTextFieldPath = new javax.swing.JTextField();
        jLabelCurrent = new javax.swing.JLabel();
        jLabelFileName = new javax.swing.JLabel();
        jScrollPaneRecordings = new javax.swing.JScrollPane();
        jListRecordings = new javax.swing.JList();
        jButtonSetPath = new javax.swing.JButton();
        jLabelList = new javax.swing.JLabel();
        jButtonRemoveFile = new javax.swing.JButton();
        jButtonSetAsCurrent = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanelDepthPref.setBorder(javax.swing.BorderFactory.createTitledBorder("Depth Generator"));

        jCheckBoxDepth.setSelected(true);
        jCheckBoxDepth.setText("Depth Image");
        jCheckBoxDepth.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBoxDepthActionPerformed(evt);
            }
        });
        jPanelDepthPref.add(jCheckBoxDepth);

        jCheckBoxDepthSkeleton.setSelected(true);
        jCheckBoxDepthSkeleton.setText("Skeleton Image");
        jCheckBoxDepthSkeleton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBoxDepthSkeletonActionPerformed(evt);
            }
        });
        jPanelDepthPref.add(jCheckBoxDepthSkeleton);

        jPanelRecording.setBorder(javax.swing.BorderFactory.createTitledBorder("Recording"));

        jLabelUser.setText("User:");

        jTextFieldUser.setText("user");
        jTextFieldUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldUserActionPerformed(evt);
            }
        });

        jLabelGesture.setText("Gesture:");

        jLabelSequence.setText("Sequence:");

        jTextFieldGesture.setText("generic");
        jTextFieldGesture.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldGestureActionPerformed(evt);
            }
        });

        jSpinnerSequence.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1)));

        jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);

        jLabelDelay.setText("Delay [s]:");

        jSpinnerDelay.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(5), Integer.valueOf(0), null, Integer.valueOf(1)));
        jSpinnerDelay.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jSpinnerDelayStateChanged(evt);
            }
        });

        jLabelTime.setText("Time [s]:");

        jSpinnerTime.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(3), Integer.valueOf(1), null, Integer.valueOf(1)));
        jSpinnerTime.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jSpinnerTimeStateChanged(evt);
            }
        });

        jPanelRecButtons.setLayout(new java.awt.GridBagLayout());

        jButtonSave.setText("Save");
        jButtonSave.setToolTipText("Save recording");
        jButtonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.ipadx = 7;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanelRecButtons.add(jButtonSave, gridBagConstraints);

        jButtonStop.setText("Stop");
        jButtonStop.setToolTipText("Stop recording");
        jButtonStop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonStopActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.ipadx = 7;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanelRecButtons.add(jButtonStop, gridBagConstraints);

        jButtonStart.setText("Start");
        jButtonStart.setToolTipText("Start recording");
        jButtonStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonStartActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.ipadx = 5;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanelRecButtons.add(jButtonStart, gridBagConstraints);

        jButtonNewSequence.setText("New");
        jButtonNewSequence.setToolTipText("Init new recording");
        jButtonNewSequence.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNewSequenceActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.ipadx = 6;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanelRecButtons.add(jButtonNewSequence, gridBagConstraints);

        jButtonReset.setText("Reset");
        jButtonReset.setToolTipText("Reset recording");
        jButtonReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonResetActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanelRecButtons.add(jButtonReset, gridBagConstraints);

        javax.swing.GroupLayout jPanelRecordingLayout = new javax.swing.GroupLayout(jPanelRecording);
        jPanelRecording.setLayout(jPanelRecordingLayout);
        jPanelRecordingLayout.setHorizontalGroup(
            jPanelRecordingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelRecordingLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelRecordingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabelSequence)
                    .addComponent(jLabelGesture)
                    .addComponent(jLabelUser)
                    .addComponent(jLabelDelay)
                    .addComponent(jLabelTime))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelRecordingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jSpinnerTime)
                    .addComponent(jTextFieldUser, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)
                    .addComponent(jTextFieldGesture)
                    .addComponent(jSpinnerDelay)
                    .addComponent(jSpinnerSequence, javax.swing.GroupLayout.DEFAULT_SIZE, 76, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanelRecButtons, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanelRecordingLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jSpinnerDelay, jSpinnerSequence, jSpinnerTime, jTextFieldGesture, jTextFieldUser});

        jPanelRecordingLayout.setVerticalGroup(
            jPanelRecordingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelRecordingLayout.createSequentialGroup()
                .addGroup(jPanelRecordingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)
                    .addGroup(jPanelRecordingLayout.createSequentialGroup()
                        .addGroup(jPanelRecordingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabelUser)
                            .addComponent(jTextFieldUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanelRecordingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabelGesture)
                            .addComponent(jTextFieldGesture, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanelRecordingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabelSequence)
                            .addComponent(jSpinnerSequence, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanelRecordingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabelDelay)
                            .addComponent(jSpinnerDelay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanelRecordingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabelTime)
                            .addComponent(jSpinnerTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanelRecordingLayout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(jPanelRecButtons, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE)))
                .addContainerGap())
        );

        jPanelData.setBorder(javax.swing.BorderFactory.createTitledBorder("Data"));

        jLabelPath.setText("Path:");

        jLabelCurrent.setText("Current recording file name:");

        jLabelFileName.setFont(new java.awt.Font("Ubuntu", 1, 15));
        jLabelFileName.setText("user_generic_0");

        jListRecordings.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jListRecordings.setToolTipText("Deselect item: [ctrl] + click");
        jListRecordings.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jListRecordingsValueChanged(evt);
            }
        });
        jScrollPaneRecordings.setViewportView(jListRecordings);

        jButtonSetPath.setText("Set");
        jButtonSetPath.setToolTipText("Set Path");
        jButtonSetPath.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSetPathActionPerformed(evt);
            }
        });

        jLabelList.setText("List recordings:");

        jButtonRemoveFile.setText("Remove");
        jButtonRemoveFile.setToolTipText("Delete selected file");
        jButtonRemoveFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRemoveFileActionPerformed(evt);
            }
        });

        jButtonSetAsCurrent.setText("Set");
        jButtonSetAsCurrent.setToolTipText("Set selected as current ");

        javax.swing.GroupLayout jPanelDataLayout = new javax.swing.GroupLayout(jPanelData);
        jPanelData.setLayout(jPanelDataLayout);
        jPanelDataLayout.setHorizontalGroup(
            jPanelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelDataLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelDataLayout.createSequentialGroup()
                        .addComponent(jLabelCurrent)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabelFileName, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabelList)
                    .addGroup(jPanelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelDataLayout.createSequentialGroup()
                            .addComponent(jLabelPath)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jTextFieldPath)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jButtonSetPath))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelDataLayout.createSequentialGroup()
                            .addComponent(jScrollPaneRecordings, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(jPanelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jButtonRemoveFile)
                                .addComponent(jButtonSetAsCurrent)))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanelDataLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButtonRemoveFile, jButtonSetAsCurrent, jButtonSetPath});

        jPanelDataLayout.setVerticalGroup(
            jPanelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelDataLayout.createSequentialGroup()
                .addGroup(jPanelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelPath)
                    .addComponent(jTextFieldPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonSetPath))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelCurrent)
                    .addComponent(jLabelFileName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelList)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelDataLayout.createSequentialGroup()
                        .addComponent(jButtonRemoveFile)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonSetAsCurrent))
                    .addComponent(jScrollPaneRecordings, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Help");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanelDepthPref, javax.swing.GroupLayout.DEFAULT_SIZE, 561, Short.MAX_VALUE)
                    .addComponent(jPanelRecording, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanelData, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanelDepthPref, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanelRecording, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanelData, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jCheckBoxDepthActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxDepthActionPerformed
        this.userTracker.setDrawDepthImage(jCheckBoxDepth.isSelected());
    }//GEN-LAST:event_jCheckBoxDepthActionPerformed

    private void jButtonStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonStartActionPerformed
        
        jButtonSave.setEnabled(false);
        jButtonStart.setEnabled(false);
        jButtonStop.setEnabled(true);
        userTracker.sequence = Sequence.newBuilder();
        userTracker.frameNumber = 1;
        
        if(delayTimeSet) {
            delayTimer.start();
        } else {
            userTracker.recording = true;
            if(recordTimeSet) {
                recordTimer.start();
            }
        }
    }//GEN-LAST:event_jButtonStartActionPerformed

    private void jCheckBoxDepthSkeletonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxDepthSkeletonActionPerformed
        this.userTracker.setDrawSkeleton(jCheckBoxDepthSkeleton.isSelected());
    }//GEN-LAST:event_jCheckBoxDepthSkeletonActionPerformed

    private void jTextFieldUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldUserActionPerformed
        createFileName();
    }//GEN-LAST:event_jTextFieldUserActionPerformed

    private void jButtonNewSequenceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNewSequenceActionPerformed
        jSpinnerSequence.setValue(jSpinnerSequence.getNextValue());        
        createFileName();
    }//GEN-LAST:event_jButtonNewSequenceActionPerformed

    private void jButtonResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonResetActionPerformed
        // TODO Reset Button - anything else?
        userTracker.sequence = Sequence.newBuilder();
        userTracker.frameNumber = 1;
        jButtonStop.setEnabled(false);
    }//GEN-LAST:event_jButtonResetActionPerformed

    private void jTextFieldGestureActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldGestureActionPerformed
        createFileName();
    }//GEN-LAST:event_jTextFieldGestureActionPerformed

    private void jButtonStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonStopActionPerformed
        userTracker.recording = false;
        jButtonSave.setEnabled(true);
        jButtonStart.setEnabled(true);
        jButtonStop.setEnabled(false);
    }//GEN-LAST:event_jButtonStopActionPerformed

    private void jSpinnerDelayStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSpinnerDelayStateChanged
        if(((Integer)jSpinnerDelay.getValue()) == 0) {
            delayTimeSet = false;
        } else {
            delayTimeSet = true;
            delayTimer.setInitialDelay(1000*(Integer)jSpinnerDelay.getValue());
        }
    }//GEN-LAST:event_jSpinnerDelayStateChanged

    private void jSpinnerTimeStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSpinnerTimeStateChanged
        if(((Integer)jSpinnerTime.getValue()) == 0) {
            recordTimeSet = false;
        } else {
            recordTimeSet = true;
            recordTimer.setInitialDelay(1000*(Integer)jSpinnerTime.getValue());
        }        
    }//GEN-LAST:event_jSpinnerTimeStateChanged

    private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed
        saveFile();
    }//GEN-LAST:event_jButtonSaveActionPerformed

    private void jButtonSetPathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSetPathActionPerformed
        path = jTextFieldPath.getText();
        //TODO: refresh list!
        createFileList();
    }//GEN-LAST:event_jButtonSetPathActionPerformed

    private void jButtonRemoveFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRemoveFileActionPerformed
        String name = "";
        if(!jListRecordings.isSelectionEmpty()) {
            if(!(name = jListRecordings.getSelectedValue().toString()).equals("")) {
                File f = new File(dir.getPath()+File.separator+name);
                f.delete();
                createFileList();
            }
        }
    }//GEN-LAST:event_jButtonRemoveFileActionPerformed

    private void jListRecordingsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListRecordingsValueChanged
        //ListSelectionModel lsm = (ListSelectionModel)evt.getSource();
        
        if(! evt.getValueIsAdjusting()) return;
            
        fileSelected = ! jListRecordings.isSelectionEmpty();

        if(fileSelected) {
            updateFileName((String)jListRecordings.getSelectedValue());            
        }

    }//GEN-LAST:event_jListRecordingsValueChanged

    
    /*
     * Delay recording & Timer recording
     */    
    ActionListener taskPerformerDelay = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            userTracker.recording = true;
            System.err.println("Recording started!");
            if(recordTimeSet) {
                recordTimer.start();
            }
        }
    };
    
    ActionListener taskPerformerTimer = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            userTracker.recording = false;
            jButtonSave.setEnabled(true);
            jButtonStart.setEnabled(true);
            jButtonStop.setEnabled(false);
            System.err.println("Recording stopped!");
        }
    };
    
    /*
     * File handling
     */
//    private void setFileName() {
//        
//    }
    
    private void saveFile() {
        File file = new File(path+fileName);
        if(file.exists()) {
            if( !optionDialog("Do you want to overwrite the selected recording?")) return;
        }
        
        try {
            output = new FileOutputStream(file);
            userTracker.sequence.setName(fileName);
            userTracker.sequence.setLabel(jTextFieldGesture.getText());
            userTracker.sequence.build().writeTo(output);
            output.close();
            System.out.println("File "+fileName+" saved.");
        } catch (IOException ex) {
            System.err.println("Error: file "+fileName+" not saved!");
            ex.printStackTrace();
        }
    }
    
    private void createFileName() {
        fileName = jTextFieldUser.getText()+"_"+jTextFieldGesture.getText()+"_"+jSpinnerSequence.getValue();
        jLabelFileName.setText(fileName);
    }
    
    private void updateFileName(String s) {
        String[] tmpStringArray = s.split("_");
        System.out.println(java.util.Arrays.toString(tmpStringArray));
        jTextFieldUser.setText(tmpStringArray[0]);
        jTextFieldGesture.setText(tmpStringArray[1]);
        jSpinnerSequence.setValue((Integer.parseInt(tmpStringArray[2])));
        fileName = s;
        jLabelFileName.setText(fileName);
    }
    
    private void createFileList() {
        dir = new File(path);
        
        if(!dir.isDirectory()) {
            // TODO: Report Error !
            return;
        }
        
                
        String[] children = dir.list();
        java.util.Arrays.sort(children);
   
        // TODO: Show only valid recording files!
        jListRecordings.setListData(children);
        
    }

    private boolean optionDialog(String msg) {
        JDialog.setDefaultLookAndFeelDecorated(true);
        int response = JOptionPane.showConfirmDialog(null, msg, "Confirm",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (response == JOptionPane.YES_OPTION) {
            return true;
        } 
        return false;
    }

    private boolean optionDialog(String msg, String title) {
        JDialog.setDefaultLookAndFeelDecorated(true);
        int response = JOptionPane.showConfirmDialog(null, msg, title,
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (response == JOptionPane.YES_OPTION) {
            return true;
        } 
        return false;
    }
    
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName()); 
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(RecorderUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new RecorderUI().setVisible(true);
                
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonNewSequence;
    private javax.swing.JButton jButtonRemoveFile;
    private javax.swing.JButton jButtonReset;
    private javax.swing.JButton jButtonSave;
    private javax.swing.JButton jButtonSetAsCurrent;
    private javax.swing.JButton jButtonSetPath;
    private javax.swing.JButton jButtonStart;
    private javax.swing.JButton jButtonStop;
    private javax.swing.JCheckBox jCheckBoxDepth;
    private javax.swing.JCheckBox jCheckBoxDepthSkeleton;
    private javax.swing.JLabel jLabelCurrent;
    private javax.swing.JLabel jLabelDelay;
    private javax.swing.JLabel jLabelFileName;
    private javax.swing.JLabel jLabelGesture;
    private javax.swing.JLabel jLabelList;
    private javax.swing.JLabel jLabelPath;
    private javax.swing.JLabel jLabelSequence;
    private javax.swing.JLabel jLabelTime;
    private javax.swing.JLabel jLabelUser;
    private javax.swing.JList jListRecordings;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanelData;
    private javax.swing.JPanel jPanelDepthPref;
    private javax.swing.JPanel jPanelRecButtons;
    private javax.swing.JPanel jPanelRecording;
    private javax.swing.JScrollPane jScrollPaneRecordings;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSpinner jSpinnerDelay;
    private javax.swing.JSpinner jSpinnerSequence;
    private javax.swing.JSpinner jSpinnerTime;
    private javax.swing.JTextField jTextFieldGesture;
    private javax.swing.JTextField jTextFieldPath;
    private javax.swing.JTextField jTextFieldUser;
    // End of variables declaration//GEN-END:variables
}
